package com.cci.kangdao.service.impl;

import com.cci.kangdao.crmapi.CRMApiUtils;
import com.cci.kangdao.crmapi.CRMResponeEntity;
import com.cci.kangdao.dao.*;
import com.cci.kangdao.dao.model.RelationShipT;
import com.cci.kangdao.dao.model.UserT;
import com.cci.kangdao.dao.model.WorkOrderPrincipalT;
import com.cci.kangdao.redis.RedisClientUtils;
import com.cci.kangdao.service.ConfirmationByServiceManagerService;
import com.cci.kangdao.task.AsyncTask;
import com.cci.kangdao.utilTool.*;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Service("ConfirmationByServiceManagerService")
public class ConfirmationByServiceManagerImpl implements ConfirmationByServiceManagerService {

	private Logger log = Logger.getLogger(this.getClass().getName());

	@Resource
	private LoginDao loginDao;

	@Autowired
	private ConfirmationByServiceManagerDao confirmationByServiceManagerDao;

	@Resource
	private CRMPlatformServiceDao platformServiceDao;

	@Resource
	private WorkOrderRepairDao workOrderRepairDao;

	@Autowired
	private ServiceManagerAffirmDao serviceManagerAffirmDao;

	@Resource
	private AsyncTask asyncTask;

	@Autowired
	private RedisClientUtils redisClientUtils;

	@Autowired
	private ServiceStationDao serviceStationDao;

	@Autowired
	private UserTDao userTDao;

	@Autowired
	private WorkOrderPrincipalTDao workOrderPrincipalTDao;

	@Autowired
	private RelationShipTDao relationShipTDao;

	@Autowired
	private WorkOrderTServiceImpl workOrderTServiceImpl;

	@Autowired
	private WorkOrderRepairDao workOrderRePairDao;


	/**
	 * DCEC商务主任消息
	 */
	private static String directorMsg = "您有新工单信息，工单编号%s，请尽快处理!";

	@Transactional
	@Override
	public ModelAndView affirm(Map<String, Object> map) {

		HttpServletResponse response = (HttpServletResponse) map.get("response");
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		try {
			// 根据App传入字段userId查询user_T表ID
			String userid = MapUtils.getString(map, "UserId");
			System.out.println(userid);
			UserT userByid = loginDao.getUserByid(userid);
			long id = userByid.getId();
			String contact = userByid.getContact();
			String phone = userByid.getPhone();
			map.put("updator", id);
			map.put("contact", contact);
			map.put("phone", phone);
			// 系统当前时间
			// 获取实际当前时间(服务器时间加8小时)
			String realCurrentTime = LocalTimeUtil.getRealCurrentTime();
			map.put("UpdateTime", (String)map.get("updateTime"));  //前端传来的这条工单的修改时间
			map.put("updateTime", realCurrentTime);
			map.put("ProcessComment","");
			// 拒绝状态 1==其他 2==用户不需要维修
			Integer refuseType = MapUtils.getInteger(map, "RefuseType");
			/**
			 * 其他，修改工单表状态为审核不通过、同步CRM、关联改派后新工单号
			 * 生成新工单、同步CRM、关联旧工单工单号、新工单状态显示：待服务商接单
			 * 用户不需要维修，直接修改工单表状态为（已取消15）、同步CRM
			 *
			 */
			JSONObject obj = new JSONObject();
			if (refuseType == 1) {
				map.put("OrderStatus", 37);// 商务处主任审核不通过
				// 修改旧工单表状态
				int updateOldWorkOrder = confirmationByServiceManagerDao.updateOldWorkOrder(map);
				if (updateOldWorkOrder > 0) {
					Map<String, Object> newmap = new HashMap<String, Object>();
					// 根据页面传过来的旧工单Id查询旧工单最新状态
					Map<String, Object> workOrderMap = new HashMap<String, Object>();
					workOrderMap = confirmationByServiceManagerDao.getCurrentWorkOrder(map);
					workOrderMap.put("ProcessorId",id);//操作人
					String serviceSubtype = MapUtils.getString(workOrderMap, "ServiceSubtype", "");
					String sellType = MapUtils.getString(workOrderMap, "SellType", "");
					// 旧工单表服务站ID
					Long OldServiceStationId = MapUtils.getLong(workOrderMap, "ServiceStationId");
					// 服务站渠道
					int OrderChannel = MapUtils.getIntValue(workOrderMap, "OrderChannel");
					map.put("OrderChannel", OrderChannel);

					// 根据服务站ID和服务站渠道查询工单状态同步crm所需要的BusinessNo（stationNo）
					Map<String, Object> ssRepairAndStationName = platformServiceDao.getStationAndRepairInfoByStationIDAndCompanyID(map);
					String BusinessNo = MapUtils.getString(ssRepairAndStationName, "BusinessNo");
					String StationName = MapUtils.getString(ssRepairAndStationName, "StationName");
					map.put("BusinessNo", BusinessNo);
					map.put("StationName", StationName);

					// 用户经度
					String userPositionLon = MapUtils.getString(workOrderMap, "LocLon");
					// 用户纬度
					String userPositionLat = MapUtils.getString(workOrderMap, "LocLat");
					// 用户经纬度
					String endLonLat = userPositionLon + "," + userPositionLat;
					// 根据服务站ID查询服务站经度纬度
					Map<String, Object> distance2 = workOrderRepairDao.getDistance(map);

					// 服务站经度纬度
					String positionLon = MapUtils.getString(distance2, "PositionLon");
					String positionLat = MapUtils.getString(distance2, "PositionLat");
					String startLonLat = positionLon + "," + positionLat;
					// 调用方法计算用户与服务站之间的距离
					Double distance = GetDistance.getDistance(startLonLat, endLonLat);
					map.put("distance", distance);

					// 旧工单编号
					String oldOrderNo = MapUtils.getString(workOrderMap, "OrderNo");
					// 旧工单ID
					Long oldOrderId = MapUtils.getLong(workOrderMap, "ID");
					map.put("oldOrderId", oldOrderId);
					map.put("oldOrderNo", oldOrderNo);
					// 生成新的工单编号
					//String newOrderNo = workOrderRepairService.getOrderNo(workOrderMap);
					/**
					 * <p>
					 *     自动生成工单编号，由 redis 更改为 sqlServer
					 * </p>
					 */
					String newOrderNo = OrderGenerateUtil.getWorkOrderNo();
					workOrderMap.put("newOrderNo", newOrderNo);
					// 将旧工单状态同步至CRM
					Map<String, Object> tbMap = new HashMap<String, Object>();
					tbMap = OrderStatusToCrmMap(workOrderMap, map,OrderChannel);// 改派时，根据服务渠道，处理不同的逻辑
					tbMap.put("phoneIMEI",MapUtils.getString(map,"IMEI",""));
					tbMap.put("positionLat",MapUtils.getFloatValue(map,"PositionLat",0));
					tbMap.put("positionLon",MapUtils.getFloatValue(map,"PositionLon",0));
					tbMap.put("location",MapUtils.getString(map,"Location",""));
					Map<String,Object> sSRepair = serviceStationDao.getStationNoAndNameByStationIdAndCompanyId(OldServiceStationId,OrderChannel);
					if(org.apache.commons.collections.MapUtils.isNotEmpty(sSRepair)){
						tbMap.put("stationName",sSRepair.get("StationName"));
					}else{
						tbMap.put("stationName","");
					}
					try {
						if (OrderChannel == 3){//DCEC
							CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi()
									.syncOrderStatusToCrm(workOrderMap.get("Abbreviation").toString(), platformServiceDao,redisClientUtils,tbMap,null);
							if(CRMres.getStatus() != 0) {
								log.error("同步工单状态至CRM失败!状态:" + CRMres.getStatus() + ",错误信息:" + CRMres.getMessage());
							}
						}else // XCEC
						{
							CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi()
									.syncOrderStatusToCrm(workOrderMap.get("Abbreviation").toString(), platformServiceDao,redisClientUtils,tbMap,null);
							if(CRMres.getStatus() != 0) {
								log.error("同步工单状态至CRM失败!状态:" + CRMres.getStatus() + ",错误信息:" + CRMres.getMessage());
							}
						}

					} catch (Exception e) {
						e.printStackTrace();
						log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(),e);
					}
					// 字段转换
					Map<String, Object> tbMap2 = new HashMap<String, Object>();
					tbMap2 = CRM_WorkOrder_Convert(workOrderMap, map, 4);
					// 生成新工单
					tbMap2.put("AssignStationTime", realCurrentTime);
					//服务站查询是否显示，  -1为不显示
					tbMap2.put("isShowStation", "");
					int createWorkOrder = confirmationByServiceManagerDao.createWorkOrder(tbMap2);
					// 新工单id
					Long newOrderId = MapUtils.getLong(tbMap2, "OrderId");

					tbMap2.put("newOrderNo", newOrderNo);
					tbMap2.put("StationNo", BusinessNo);
					tbMap2.put("StationName", StationName);
					map.put("newOrderId", newOrderId);
					map.put("OrderStatus", 4);
					// 旧工单关联新工单表id
					confirmationByServiceManagerDao.updateRelOrderId(map);
					if (createWorkOrder > 0) {

						// 新工单id
						map.put("OrderId", newOrderId);

						// 根据服务站id查询站长、服务商信息员
						List<Map<String, Object>> messengerAndStationmaster = serviceManagerAffirmDao.getMessengerAndStationmaster(map);
						if (messengerAndStationmaster != null) {
							for (Map<String, Object> map2 : messengerAndStationmaster) {
								long UserId = (long) map2.get("UserID");
								map.put("UserId", UserId);
								//newmap.put("OrderId", map.get("OrderId"));
								newmap.put("OrderId", newOrderId);
								newmap.put("OrderStatus", 4);
								newmap.put("UserId", UserId);
								newmap.put("updator", id);
								newmap.put("updateTime", realCurrentTime);

								// 插入工单负责人表
								int insertWorkOrderPrincipal = serviceManagerAffirmDao.insertWorkOrderPrincipal(newmap);
								System.out.println(insertWorkOrderPrincipal);
							}
						}

						// 将工单信息同步至CRM接口
						// 字段转换（APP接口字段名与CRM接口字段名不一致。）
						Map<String, Object> tbMap3 = new HashMap<String, Object>();
						tbMap3 = APP2CRM_WorkOrder_Convert(tbMap2);
						tbMap3.put("billStatus", 4);

						try {
							if (OrderChannel == 3) {//DCEC
								CRMResponeEntity CRMres1 = CRMApiUtils.getCRMServiceApi()
										.syncOrderStatusToCrm(workOrderMap.get("Abbreviation").toString(), platformServiceDao,redisClientUtils,tbMap3,null);
								if(CRMres1.getStatus() != 0) {
									log.error("同步工单信息至CRM失败!状态:" + CRMres1.getStatus() + ",错误信息:" + CRMres1.getMessage());
								}
							}else
							{
								Map<String, Object> xcecNewWOrkOrderStatusMap = new HashMap<String, Object>();
								xcecNewWOrkOrderStatusMap = XCECNewOrderStatusToCrmMap(workOrderMap, map);
								CRMResponeEntity CRMres1 = CRMApiUtils.getCRMServiceApi()
										.syncOrderStatusToCrm(workOrderMap.get("Abbreviation").toString(), platformServiceDao,redisClientUtils,xcecNewWOrkOrderStatusMap,null);
								if(CRMres1.getStatus() != 0) {
									log.error("同步工单状态至CRM失败!状态:" + CRMres1.getStatus() + ",错误信息:" + CRMres1.getMessage());
								}
							}

						} catch (Exception e) {
							e.printStackTrace();
							log.error("同步工单信息至CRM失败!错误信息:" + e.getMessage(),e);
						}

						// 插入工单操作记录表，新工单状态为4、新工单id
						map.put("ProcessStatus", 4);
						map.put("ProcessComment", map.get("RefuseContent"));
						int insertWorkOrderFlow = serviceManagerAffirmDao.insertWorkOrderFlow(map);
						System.out.println(insertWorkOrderFlow);

						// 插入工单操作记录表，旧工单状态为3、旧工单id
//						map.put("OrderId", oldOrderId);
//						map.put("ProcessStatus", 37);
//						int insertWorkOrderFlow2 = serviceManagerAffirmDao.insertWorkOrderFlow(map);
//						System.out.println(insertWorkOrderFlow2);

						// 推送指派消息给新工单服务站长
						map.put("roleNames", "'站长','服务商信息员'");
						map.put("roleNo", "'R0041','R0069'");
						List<Map<String, Object>> sendList = new ArrayList<Map<String, Object>>();
						sendList = workOrderRepairDao.getSendList(map, Arrays.asList("R0041","R0069"));
						if (null != sendList && sendList.size() > 0) {
							// 准备发送信息
							Map<String, Object> otherMap = new HashMap<String, Object>();

							String smsgbody = "您有新工单信息，工单号 " + newOrderNo + "，";
							if(OrderChannel == 1){
								smsgbody = smsgbody + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
							}
							smsgbody = smsgbody + "请尽快处理！";
							String stransmsg = "您有新工单信息，工单号 " + newOrderNo + "，";
							if(OrderChannel == 1){
								stransmsg = stransmsg + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
							}
							stransmsg = stransmsg + "请尽快处理！";

							otherMap.put("msgBody", smsgbody);
							otherMap.put("msgTransMsg", stransmsg);
							otherMap.put("msgTitle", "新工单提醒");
							otherMap.put("function", 2);
							otherMap.put("category", 1);
							otherMap.put("Creator", id);
							otherMap.put("CreateTime", realCurrentTime);

							// 开始发送消息(返回结果集为发送结果，要存入数据库，作为记录)
							List<Map<String, Object>> sendMsgResultList = asyncTask
                                    .sendMsg(tbMap2, sendList, 1, 1, otherMap);
							// 将信息发送结果记录到数据库
							if(CollectionUtils.isNotEmpty(sendMsgResultList)){
								int saveMsgOperationResult = workOrderRepairDao.saveMsgOperation(sendMsgResultList);
							}
						}
						// 推送取消消息给旧工单服务站长
						if (OrderChannel != 3) {  // 东康  旧单子将不会看到推送
							List<Map<String, Object>> sendList1 = new ArrayList<Map<String, Object>>();
							map.put("ServiceStationId", OldServiceStationId);
							sendList1 = workOrderRepairDao.getSendList(map,Arrays.asList("R0041","R0069"));
							if (null != sendList1 && sendList1.size() > 0) {
								// 准备发送信息
								Map<String, Object> otherMap = new HashMap<String, Object>();
								String smsgbody = "您有工单取消，工单号 " + oldOrderNo + "，";
								if(OrderChannel == 1){
									smsgbody = smsgbody + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
								}
								smsgbody = smsgbody + "请查看!";
								String stransmsg = "您有工单取消，工单号 " + oldOrderNo + "，";
								if(OrderChannel == 1){
									stransmsg = stransmsg + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
								}
								stransmsg = stransmsg + "请查看!";
								otherMap.put("msgBody", smsgbody);
								otherMap.put("msgTransMsg", stransmsg);
								otherMap.put("msgTitle", "工单取消");
								otherMap.put("function", 9);
								otherMap.put("category", 4);
								otherMap.put("Creator", id);
								otherMap.put("CreateTime", realCurrentTime);
								// 开始发送消息(返回结果集为发送结果，要存入数据库，作为记录)
								List<Map<String, Object>> sendMsgResultList = asyncTask
										.sendMsg(workOrderMap, sendList1, 1, 1, otherMap);
								// 将信息发送结果记录到数据库
								if (CollectionUtils.isNotEmpty(sendMsgResultList)) {
									int saveMsgOperationResult = workOrderRepairDao.saveMsgOperation(sendMsgResultList);
								}
							}
						}
						try {
							obj.put("status", 0);
							obj.put("msg", "");
							obj.put("data", "");
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						ParameterTool.writeResponse(response, obj.toString());
					}
				}else {
					obj.put("status", SMSEnum.type21.getIndex());
					obj.put("msg", SMSEnum.type21.getName());
					obj.put("data", "");
					// 主动回滚事务
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					//返回客户
					ParameterTool.writeResponse(response, obj.toString());
					return null;
				}
			}
			if (refuseType == 2) {
				map.put("OrderStatus", 15);
				// 修改工单表状态
				int updateOldWorkOrder = confirmationByServiceManagerDao.updateOldWorkOrder(map);

				if (updateOldWorkOrder > 0) {
					// 根据页面传过来的工单Id查询工单最新状态
					Map<String, Object> workOrderMap = new HashMap<String, Object>();
					workOrderMap = confirmationByServiceManagerDao.getCurrentWorkOrder(map);
					String serviceSubtype = MapUtils.getString(workOrderMap, "ServiceSubtype", "");
					String sellType = MapUtils.getString(workOrderMap, "SellType", "");
					// 工单表服务站ID
					Long ServiceStationId = MapUtils.getLong(workOrderMap, "ServiceStationId");
					// 服务站渠道
					int OrderChannel = MapUtils.getIntValue(workOrderMap, "OrderChannel");
					map.put("ServiceStationId", ServiceStationId);
					map.put("OrderChannel", OrderChannel);
					// 根据服务站ID和服务站渠道查询工单状态同步crm所需要的BusinessNo（stationNo）
					Map<String, Object> ssRepair = confirmationByServiceManagerDao.getSSRepair(map);
					String BusinessNo = MapUtils.getString(ssRepair, "BusinessNo");
					map.put("BusinessNo", BusinessNo);

					// 旧工单编号
					String oldOrderNo = MapUtils.getString(workOrderMap, "OrderNo");
					// 将工单状态同步至CRM
					Map<String, Object> tbMap = new HashMap<String, Object>();
					tbMap = OrderStatusToCrmMapByServiceManager(workOrderMap,map);
					try {
						CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi()
								.syncOrderStatusToCrm(workOrderMap.get("Abbreviation").toString(), platformServiceDao,redisClientUtils,tbMap,null);
						if(CRMres.getStatus() != 0) {
							log.error("同步工单状态至CRM失败!状态:" + CRMres.getStatus() + ",错误信息:" + CRMres.getMessage());
						}
					} catch (Exception e) {
						e.printStackTrace();
						log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(),e);
					}

					// 插入工单操作记录表
					map.put("ProcessStatus", 15);
					map.put("ProcessComment", map.get("RefuseContent"));
					int insertWorkOrderFlow = serviceManagerAffirmDao.insertWorkOrderFlow(map);
					System.out.println(insertWorkOrderFlow);

					if (OrderChannel != 3) {  // 东康  旧单子将不会看到推送
						map.put("roleNames", "'站长','服务商信息员'");
						map.put("roleNo", "'R0041','R0069'");
						List<Map<String, Object>> sendList = new ArrayList<Map<String, Object>>();
						sendList = workOrderRepairDao.getSendList(map,Arrays.asList("R0041","R0069"));
						if (null != sendList && sendList.size() > 0) {
							// 准备发送信息
							Map<String, Object> otherMap = new HashMap<String, Object>();
							String smsgbody = "您有工单取消，工单号 " + oldOrderNo + "，";
							if(OrderChannel == 1){
								smsgbody = smsgbody + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
							}
							smsgbody = smsgbody + "请查看!";
							String stransmsg = "您有工单取消，工单号 " + oldOrderNo + "，";
							if(OrderChannel == 1){
								stransmsg = stransmsg + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
							}
							stransmsg = stransmsg + "请查看!";
							otherMap.put("msgBody", smsgbody);
							otherMap.put("msgTransMsg", stransmsg);
							otherMap.put("msgTitle", "工单取消");
							otherMap.put("function", 9);
							otherMap.put("category", 4);
							otherMap.put("Creator", id);
							otherMap.put("CreateTime", realCurrentTime);
							// 开始发送消息(返回结果集为发送结果，要存入数据库，作为记录)
							List<Map<String, Object>> sendMsgResultList = asyncTask.sendMsg(workOrderMap,
									sendList, 1, 1, otherMap);
							// 将信息发送结果记录到数据库
							if (CollectionUtils.isNotEmpty(sendMsgResultList)) {
								int saveMsgOperationResult = workOrderRepairDao.saveMsgOperation(sendMsgResultList);
							}
						}
					}
					try {
						obj.put("status", 0);
						obj.put("msg", "");
						obj.put("data", "");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					ParameterTool.writeResponse(response, obj.toString());
					// 插入消息提醒记录表
					// int insertNotifyRecord1 =
					// serviceManagerAffirmDao.insertNotifyRecord1(map);
					// int insertNotifyRecord2 =
					// serviceManagerAffirmDao.insertNotifyRecord2(map);
					// System.out.println(insertNotifyRecord1+"---"+insertNotifyRecord2);
				}else {
					obj.put("status", SMSEnum.type21.getIndex());
					obj.put("msg", SMSEnum.type21.getName());
					obj.put("data", "");
					// 主动回滚事务
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					//返回客户
					ParameterTool.writeResponse(response, obj.toString());
					return null;
				}
			}

		} catch (Exception ex) {
			// TODO: handle exception
			log.error(ex.getMessage(), ex);
			ParameterTool.writeErrorResponse(response);
			// 主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
		return null;
	}



	//服务经理转派服务站提交
	@Transactional
	@Override
	public ModelAndView affirmNew(Map<String, Object> map) {

		HttpServletResponse response = (HttpServletResponse) map.get("response");
		HttpServletRequest request = (HttpServletRequest) map.get("request");
		try {
			// 根据App传入字段userId查询user_T表ID
			String userid = MapUtils.getString(map, "UserId");
			System.out.println(userid);
			UserT userByid = loginDao.getUserByid(userid);
			long id = userByid.getId();
			String contact = userByid.getContact();
			String phone = userByid.getPhone();
			map.put("updator", id);
			map.put("contact", contact);
			map.put("phone", phone);
			// 系统当前时间
			// 获取实际当前时间(服务器时间加8小时)
			String realCurrentTime = LocalTimeUtil.getRealCurrentTime();
			map.put("UpdateTime", (String)map.get("updateTime"));  //前端传来的这条工单的修改时间
			map.put("updateTime", realCurrentTime);
			map.put("ProcessComment","");
			// 拒绝状态 1==其他 2==用户不需要维修
			Integer refuseType = MapUtils.getInteger(map, "RefuseType");

			/**
			 * 其他，修改工单表状态为审核不通过、同步CRM、关联改派后新工单号
			 * 生成新工单、同步CRM、关联旧工单工单号、新工单状态显示：待服务商接单
			 * 用户不需要维修，直接修改工单表状态为（已取消15）、同步CRM
			 */
			JSONObject obj = new JSONObject();
			if (refuseType == 1) {
				map.put("OrderStatus", 3);// 审核不通过
				// 修改旧工单表状态
				int updateOldWorkOrder = confirmationByServiceManagerDao.updateOldWorkOrder(map);
				if (updateOldWorkOrder > 0) {
					Map<String, Object> newmap = new HashMap<String, Object>();
					// 根据页面传过来的旧工单Id查询旧工单最新状态
					Map<String, Object> workOrderMap = new HashMap<String, Object>();
					workOrderMap = confirmationByServiceManagerDao.getCurrentWorkOrder(map);
					workOrderMap.put("ProcessorId",id);//操作人
					String serviceSubtype = MapUtils.getString(workOrderMap, "ServiceSubtype", "");
					String sellType = MapUtils.getString(workOrderMap, "SellType", "");
					// 旧工单表服务站ID
					Long OldServiceStationId = MapUtils.getLong(workOrderMap, "ServiceStationId");
					// 服务站渠道
					int OrderChannel = MapUtils.getIntValue(workOrderMap, "OrderChannel");
					map.put("OrderChannel", OrderChannel);
					// 根据服务站ID和服务站渠道查询工单状态同步crm所需要的BusinessNo（stationNo）
					Map<String, Object> ssRepairAndStationName = platformServiceDao.getStationAndRepairInfoByStationIDAndCompanyID(map);
					String BusinessNo = MapUtils.getString(ssRepairAndStationName, "BusinessNo");
					String StationName = MapUtils.getString(ssRepairAndStationName, "StationName");
					map.put("BusinessNo", BusinessNo);
					map.put("StationName", StationName);

					// 用户经度
					String userPositionLon = MapUtils.getString(workOrderMap, "LocLon");
					// 用户纬度
					String userPositionLat = MapUtils.getString(workOrderMap, "LocLat");
					// 用户经纬度
					String endLonLat = userPositionLon + "," + userPositionLat;
					// 根据服务站ID查询服务站经度纬度
					Map<String, Object> distance2 = workOrderRepairDao.getDistance(map);

					// 服务站经度纬度
					String positionLon = MapUtils.getString(distance2, "PositionLon");
					String positionLat = MapUtils.getString(distance2, "PositionLat");
					String startLonLat = positionLon + "," + positionLat;

					/**
					 * 算出新服务站与维修地点的距离
					 */
					// 调用方法计算用户与服务站之间的距离
					Double distance = GetDistance.getDistance(startLonLat, endLonLat);
					map.put("distance", distance);

					// 旧工单编号
					String oldOrderNo = MapUtils.getString(workOrderMap, "OrderNo");
					// 旧工单ID
					Long oldOrderId = MapUtils.getLong(workOrderMap, "ID");
					map.put("oldOrderId", oldOrderId);
					map.put("oldOrderNo", oldOrderNo);
					// 生成新的工单编号
					//String newOrderNo = workOrderRepairService.getOrderNo(workOrderMap);
					/**
					 * <p>
					 *     自动生成工单编号，由 redis 更改为 sqlServer
					 * </p>
					 */
					String newOrderNo = OrderGenerateUtil.getWorkOrderNo();
					workOrderMap.put("newOrderNo", newOrderNo);
					// 将旧工单状态同步至CRM
					Map<String, Object> tbMap = new HashMap<String, Object>();
					tbMap = OrderStatusToCrmMap(workOrderMap, map,OrderChannel);// 改派时，根据服务渠道，处理不同的逻辑
					tbMap.put("phoneIMEI",MapUtils.getString(map,"IMEI",""));
					tbMap.put("positionLat",MapUtils.getFloatValue(map,"PositionLat",0));
					tbMap.put("positionLon",MapUtils.getFloatValue(map,"PositionLon",0));
					tbMap.put("location",MapUtils.getString(map,"Location",""));
					Map<String,Object> sSRepair = serviceStationDao.getStationNoAndNameByStationIdAndCompanyId(OldServiceStationId,OrderChannel);
					if(org.apache.commons.collections.MapUtils.isNotEmpty(sSRepair)){
						tbMap.put("stationName",sSRepair.get("StationName"));
					}else{
						tbMap.put("stationName","");
					}
					try {
						if (OrderChannel == 3){//DCEC
							CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi()
									.syncOrderStatusToCrm(workOrderMap.get("Abbreviation").toString(), platformServiceDao,redisClientUtils,tbMap,null);
							if(CRMres.getStatus() != 0) {
								log.error("同步工单状态至CRM失败!状态:" + CRMres.getStatus() + ",错误信息:" + CRMres.getMessage());
							}
						}else // XCEC
						{
							CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi()
									.syncOrderStatusToCrm(workOrderMap.get("Abbreviation").toString(), platformServiceDao,redisClientUtils,tbMap,null);
							if(CRMres.getStatus() != 0) {
								log.error("同步工单状态至CRM失败!状态:" + CRMres.getStatus() + ",错误信息:" + CRMres.getMessage());
							}
						}

					} catch (Exception e) {
						e.printStackTrace();
						log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(),e);
					}

					/**
					 * 2021-06-22
					 * DCEC新需求：
					 * 旧->当服务经理指派新服务站后，旧工单作废，生成新的工单(待服务商接单)
					 * 新->当服务经理指派新服务站后，增加了新的流程，需要被商务处主任审核后，才能进入待服务商接单状态
					 */
				    Integer orderStatus = 4;
				    // 如果当前工单是DCEC渠道的那么设置新工单的状态为：待商务处主任审核
					if(OrderChannel == 3) {
						// 设置工单的状态为待商务处主任审核
						orderStatus = 36;
					}

					// 字段转换
					Map<String, Object> tbMap2 = new HashMap<String, Object>();
					tbMap2 = CRM_WorkOrder_Convert(workOrderMap, map, orderStatus);
					// 生成新工单
					tbMap2.put("AssignStationTime", realCurrentTime);
					//服务站查询是否显示，  -1为不显示
					tbMap2.put("isShowStation", "");
					if (OrderChannel == 3) {
						tbMap2.put("isShowStation", -1);
					}
					int createWorkOrder = confirmationByServiceManagerDao.createWorkOrder(tbMap2);

					// 新工单id
					Long newOrderId = MapUtils.getLong(tbMap2, "OrderId");

					tbMap2.put("newOrderNo", newOrderNo);
					tbMap2.put("StationNo", BusinessNo);
					tbMap2.put("StationName", StationName);
					map.put("newOrderId", newOrderId);


					map.put("OrderStatus", 4);

					map.put("OrderId", newOrderId);

					// 商务处主任
					Map<String, Object> businessDirector = null;

					// 旧工单关联新工单表id
					confirmationByServiceManagerDao.updateRelOrderId(map);
					if (createWorkOrder > 0) {
						if(OrderChannel == 3) {
							/**
							 * DCEC渠道的工单会入待商务主任审核状态
							 * 生成工单负责人
							 */
							Long newServiceStationId = MapUtils.getLong(map, "ServiceStationId");
							// 查询出新服务站对应的商务处主任
							List<Map<String, Object>> businessDirectorList = userTDao.getBusinessDirectorDcecByServiceStationId(newServiceStationId);
							log.info(String.format("DCEC渠道 服务站id:%s 的商务处主任为:%s", newServiceStationId, businessDirectorList));

							if(CollectionUtils.isNotEmpty(businessDirectorList)) {
								businessDirector = businessDirectorList.get(0);

								List<WorkOrderPrincipalT> wops = new ArrayList<>();
								WorkOrderPrincipalT wop = new WorkOrderPrincipalT();
								wop.setOrderId(newOrderId);
								wop.setOrderStatus(36);
								wop.setIsPrincipal(1);
								wop.setUserId(MapUtils.getLongValue(businessDirector, "userId"));
								wop.setFlag(0);
								wop.setCreator(id);
								wop.setCreateTime(realCurrentTime);

								wops.add(wop);
								workOrderPrincipalTDao.insertBatchSelective(wops);
							}else {
								log.error(String.format("未找到DCEC渠道 服务站id:%s 的商务处主任，该工单可能无法处理", newServiceStationId));
								ParameterTool.writeResponse(response, 4, "未找到服务站的商务处主任");
								throw new RuntimeException("未找到服务站的商务处主任");
							}
						}else {
							// 根据服务站id查询站长、服务商信息员
							List<Map<String, Object>> messengerAndStationmaster = serviceManagerAffirmDao.getMessengerAndStationmaster(map);
							if (messengerAndStationmaster != null) {
								for (Map<String, Object> map2 : messengerAndStationmaster) {
									long UserId = (long) map2.get("UserID");
									map.put("UserId", UserId);
									//newmap.put("OrderId", map.get("OrderId"));
									newmap.put("OrderId", newOrderId);
									newmap.put("OrderStatus", orderStatus);
									newmap.put("UserId", UserId);
									newmap.put("updator", id);
									newmap.put("updateTime", realCurrentTime);
									// 插入工单负责人表
									int insertWorkOrderPrincipal = serviceManagerAffirmDao.insertWorkOrderPrincipal(newmap);
								}
							}
						}

						// 将工单信息同步至CRM接口
						// 字段转换（APP接口字段名与CRM接口字段名不一致。）
						Map<String, Object> tbMap3 = new HashMap<String, Object>();
						tbMap3 = APP2CRM_WorkOrder_Convert(tbMap2);
						try {
							/**
							 * DCEC渠道的工单这里未同步新的工单信息到crm是因为上面在同步旧工单的时候，crm系统会生成新的服务工单，所以不需要在同步
							 */
							if (OrderChannel == 3) {//DCEC
//								CRMResponeEntity CRMres1 = CRMApiUtils.getCRMServiceApi()
//										.syncAppOrderInfoToCRM(workOrderMap.get("Abbreviation").toString(), platformServiceDao,redisClientUtils,tbMap3);
//								if(CRMres1.getStatus() != 0) {
//									log.error("同步工单信息至CRM失败!状态:" + CRMres1.getStatus() + ",错误信息:" + CRMres1.getMessage());
//								}
							}else
							{
								Map<String, Object> xcecNewWOrkOrderStatusMap = new HashMap<String, Object>();
								xcecNewWOrkOrderStatusMap = XCECNewOrderStatusToCrmMap(workOrderMap, map);
								CRMResponeEntity CRMres1 = CRMApiUtils.getCRMServiceApi()
										.syncOrderStatusToCrm(workOrderMap.get("Abbreviation").toString(), platformServiceDao,redisClientUtils,xcecNewWOrkOrderStatusMap,null);
								if(CRMres1.getStatus() != 0) {
									log.error("同步工单状态至CRM失败!状态:" + CRMres1.getStatus() + ",错误信息:" + CRMres1.getMessage());
								}
							}

						} catch (Exception e) {
							e.printStackTrace();
							log.error("同步工单信息至CRM失败!错误信息:" + e.getMessage(),e);
						}

						// 插入工单操作记录表，新工单状态为、新工单id
						map.put("ProcessStatus", orderStatus);
						map.put("ProcessComment", map.get("RefuseContent"));
						int insertWorkOrderFlow = serviceManagerAffirmDao.insertWorkOrderFlow(map);

						// 插入工单操作记录表，旧工单状态为3、旧工单id
						map.put("OrderId", oldOrderId);
						map.put("ProcessStatus", 3);

						int insertWorkOrderFlow2 = serviceManagerAffirmDao.insertWorkOrderFlow(map);

						// 推送指派消息给新工单服务站长
						map.put("roleNames", "'站长','服务商信息员'");
						map.put("roleNo", "'R0041','R0069'");

						/**
						 * DCEC渠道：
						 * 由于新需求的变更，当服务经理重新指派服务站后，新工单不会直接进入待服务商接单状态，而是进入待商务处主任审核状态
						 * 因此DCEC渠道的不需要给服务站发送消息提醒而是要给商务处主任发送消息，O(∩_∩)O哈哈~
						 */
						if(OrderChannel == 3) {
							// 给新服务站的商务处主任发送消息提醒
							// 商务处主任的userId
							Long userId = MapUtils.getLong(businessDirector, "userId");
							// 商务处主任的手机号
							String directorPhone = MapUtils.getString(businessDirector, "phone");
							// 商务处主任的用户名
							String username = MapUtils.getString(businessDirector, "username");

							// 查询出商务处主任的ClientID
							RelationShipT relationShip = relationShipTDao.getClientIdByUserNameString(username);

							// 消息内容
							String content = String.format(directorMsg, newOrderNo);

							List<Map<String, Object>> notifyRecordList = new ArrayList<>();

							// 短信推送
							String smsResult = SmsUtils.sendMessage(directorPhone, content);

							Map<String, Object> smsNotifyRecord = workOrderTServiceImpl.saveMsgOperation(newOrderId, 2, 1, userId, content, 1, realCurrentTime, String.format("%s发送状态:%s", directorPhone, smsResult), id);

							String clientId = "";
							boolean result = false;
							// App推送
							if(null != relationShip) {
								clientId = relationShip.getClientId();
								result = NotifyUtil.push2Single(clientId, content, content);
							}
							Map<String, Object> appNotifyRecord = workOrderTServiceImpl.saveMsgOperation(newOrderId, 2, 1, userId, content, 2, realCurrentTime, String.format("%s发送状态:%s", clientId, result), id);

							notifyRecordList.add(smsNotifyRecord);
							notifyRecordList.add(appNotifyRecord);
							if (CollectionUtils.isNotEmpty(notifyRecordList)) {
								workOrderRePairDao.saveMsgOperation(notifyRecordList);
							}

						}else {
							/**
							 * 推送消息给新服务站站长、信息员
							 */
							List<Map<String, Object>> sendList = new ArrayList<Map<String, Object>>();
							if(map.containsKey("ServiceStationId") && StringUtils.isNotBlank(MapUtils.getString(map,"ServiceStationId"))){
								sendList = workOrderRepairDao.getSendList(map,Arrays.asList("R0041","R0069"));
							}
							if (null != sendList && sendList.size() > 0) {
								// 准备发送信息
								Map<String, Object> otherMap = new HashMap<String, Object>();
								String smsgbody = "您有新工单信息，工单号 " + newOrderNo + "，";
								if(OrderChannel == 1){
									smsgbody = smsgbody + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
								}
								smsgbody = smsgbody + "请尽快处理！";
								String stransmsg = "您有新工单信息，工单号 " + newOrderNo + "，";
								if(OrderChannel == 1){
									stransmsg = stransmsg + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
								}
								stransmsg = stransmsg + "请尽快处理！";
								otherMap.put("msgBody", smsgbody);
								otherMap.put("msgTransMsg", stransmsg);
								otherMap.put("msgTitle", "新工单提醒");
								otherMap.put("function", 2);
								otherMap.put("category", 1);
								otherMap.put("Creator", id);
								otherMap.put("CreateTime", realCurrentTime);

								// 开始发送消息(返回结果集为发送结果，要存入数据库，作为记录)
								List<Map<String, Object>> sendMsgResultList = asyncTask
										.sendMsg(workOrderMap, sendList, 1, 1, otherMap);
								// 将信息发送结果记录到数据库
								if(CollectionUtils.isNotEmpty(sendMsgResultList)){
									int saveMsgOperationResult = workOrderRepairDao.saveMsgOperation(sendMsgResultList);
								}
							}
						}


						/**
						 *  推送取消消息给旧工单服务站长
						 */
						if (OrderChannel != 3) {  // 东康  旧单子将不会看到推送
							List<Map<String, Object>> sendList1 = new ArrayList<Map<String, Object>>();
							map.put("ServiceStationId", OldServiceStationId);
							sendList1 = workOrderRepairDao.getSendList(map,Arrays.asList("R0041","R0069"));
							if (null != sendList1 && sendList1.size() > 0) {
								// 准备发送信息
								Map<String, Object> otherMap = new HashMap<String, Object>();
								String smsgbody = "您有工单取消，工单号 " + oldOrderNo + "，";
								if(OrderChannel == 1){
									smsgbody = smsgbody + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
								}
								smsgbody = smsgbody + "请查看!";
								String stransmsg = "您有工单取消，工单号 " + oldOrderNo + "，";
								if(OrderChannel == 1){
									stransmsg = stransmsg + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
								}
								stransmsg = stransmsg + "请查看!";
								otherMap.put("msgBody", smsgbody);
								otherMap.put("msgTransMsg", stransmsg);
								otherMap.put("msgTitle", "工单取消");
								otherMap.put("function", 9);
								otherMap.put("category", 4);
								otherMap.put("Creator", id);
								otherMap.put("CreateTime", realCurrentTime);
								// 开始发送消息(返回结果集为发送结果，要存入数据库，作为记录)
								List<Map<String, Object>> sendMsgResultList = asyncTask
										.sendMsg(workOrderMap, sendList1, 1, 1, otherMap);
								// 将信息发送结果记录到数据库
								if (CollectionUtils.isNotEmpty(sendMsgResultList)) {
									int saveMsgOperationResult = workOrderRepairDao.saveMsgOperation(sendMsgResultList);
								}
							}
						} else {
							//只有服务站报的单子，可发送消息通知
							Integer orderSource = (Integer) workOrderMap.get("OrderSource");
							if (orderSource == 1 || orderSource == 3) {
								List<Map<String, Object>> sendList1 = new ArrayList<Map<String, Object>>();
								map.put("ServiceStationId", OldServiceStationId);
								sendList1 = workOrderRepairDao.getSendList(map,Arrays.asList("R0041","R0069"));
								if (null != sendList1 && sendList1.size() > 0) {
									// 准备发送信息
									Map<String, Object> otherMap = new HashMap<String, Object>();
									String smsgbody = "您有工单取消，工单号 " + oldOrderNo + "，";
									if(OrderChannel == 1){
										smsgbody = smsgbody + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
									}
									smsgbody = smsgbody + "请查看!";
									String stransmsg = "您有工单取消，工单号 " + oldOrderNo + "，";
									if(OrderChannel == 1){
										stransmsg = stransmsg + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
									}
									stransmsg = stransmsg + "请查看!";
									otherMap.put("msgBody", smsgbody);
									otherMap.put("msgTransMsg", stransmsg);
									otherMap.put("msgTitle", "工单取消");
									otherMap.put("function", 9);
									otherMap.put("category", 4);
									otherMap.put("Creator", id);
									otherMap.put("CreateTime", realCurrentTime);
									// 开始发送消息(返回结果集为发送结果，要存入数据库，作为记录)
									List<Map<String, Object>> sendMsgResultList = asyncTask
											.sendMsg(workOrderMap, sendList1, 1, 1, otherMap);
									// 将信息发送结果记录到数据库
									if (CollectionUtils.isNotEmpty(sendMsgResultList)) {
										int saveMsgOperationResult = workOrderRepairDao.saveMsgOperation(sendMsgResultList);
									}
								}
							}
						}

						try {
							obj.put("status", 0);
							obj.put("msg", "");
							obj.put("data", "");
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						ParameterTool.writeResponse(response, obj.toString());
					}
				}else {
					obj.put("status", SMSEnum.type21.getIndex());
					obj.put("msg", SMSEnum.type21.getName());
					obj.put("data", "");
					// 主动回滚事务
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					//返回客户
					ParameterTool.writeResponse(response, obj.toString());
					return null;
				}
			}
			if (refuseType == 2) {
				map.put("OrderStatus", 15);
				// 修改工单表状态
				int updateOldWorkOrder = confirmationByServiceManagerDao.updateOldWorkOrder(map);

				if (updateOldWorkOrder > 0) {
					// 根据页面传过来的工单Id查询工单最新状态
					Map<String, Object> workOrderMap = new HashMap<String, Object>();
					workOrderMap = confirmationByServiceManagerDao.getCurrentWorkOrder(map);
					String serviceSubtype = MapUtils.getString(workOrderMap, "ServiceSubtype", "");
					String sellType = MapUtils.getString(workOrderMap, "SellType", "");

					// 工单表服务站ID
					Long ServiceStationId = MapUtils.getLong(workOrderMap, "ServiceStationId");
					// 服务站渠道
					int OrderChannel = MapUtils.getIntValue(workOrderMap, "OrderChannel");
					map.put("ServiceStationId", ServiceStationId);
					map.put("OrderChannel", OrderChannel);
					// 根据服务站ID和服务站渠道查询工单状态同步crm所需要的BusinessNo（stationNo）
					Map<String, Object> ssRepair = confirmationByServiceManagerDao.getSSRepair(map);
					String BusinessNo = MapUtils.getString(ssRepair, "BusinessNo");
					map.put("BusinessNo", BusinessNo);

					// 旧工单编号
					String oldOrderNo = MapUtils.getString(workOrderMap, "OrderNo");
					// 将工单状态同步至CRM
					Map<String, Object> tbMap = new HashMap<String, Object>();
					tbMap = OrderStatusToCrmMapByServiceManager(workOrderMap,map);
					try {
						CRMResponeEntity CRMres = CRMApiUtils.getCRMServiceApi()
								.syncOrderStatusToCrm(workOrderMap.get("Abbreviation").toString(), platformServiceDao,redisClientUtils,tbMap,null);
						if(CRMres.getStatus() != 0) {
							log.error("同步工单状态至CRM失败!状态:" + CRMres.getStatus() + ",错误信息:" + CRMres.getMessage());
						}
					} catch (Exception e) {
						e.printStackTrace();
						log.error("同步工单状态至CRM失败!错误信息:" + e.getMessage(),e);
					}

					// 插入工单操作记录表
					map.put("ProcessStatus", 15);
					map.put("ProcessComment", map.get("RefuseContent"));
					int insertWorkOrderFlow = serviceManagerAffirmDao.insertWorkOrderFlow(map);
					System.out.println(insertWorkOrderFlow);

					if (OrderChannel != 3) {  // 东康  旧单子将不会看到推送
						map.put("roleNames", "'站长','服务商信息员'");
						map.put("roleNo", "'R0041','R0069'");
						List<Map<String, Object>> sendList = new ArrayList<Map<String, Object>>();
						sendList = workOrderRepairDao.getSendList(map,Arrays.asList("R0041","R0069"));
						if (null != sendList && sendList.size() > 0) {
							//准备发送信息
							Map<String, Object> otherMap = new HashMap<String, Object>();
							String smsgbody = "您有工单取消，工单号 " + oldOrderNo + "，";
							if(OrderChannel == 1){
								smsgbody = smsgbody + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
							}
							smsgbody = smsgbody + "请查看!";
							String stransmsg = "您有工单取消，工单号 " + oldOrderNo + "，";
							if(OrderChannel == 1){
								stransmsg = stransmsg + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
							}
							stransmsg = stransmsg + "请查看!";
							otherMap.put("msgBody", smsgbody);
							otherMap.put("msgTransMsg", stransmsg);
							otherMap.put("msgTitle", "工单取消");
							otherMap.put("function", 9);
							otherMap.put("category", 4);
							otherMap.put("Creator", id);
							otherMap.put("CreateTime", realCurrentTime);
							// 开始发送消息(返回结果集为发送结果，要存入数据库，作为记录)
							List<Map<String, Object>> sendMsgResultList = asyncTask.sendMsg(workOrderMap,
									sendList, 1, 1, otherMap);
							// 将信息发送结果记录到数据库
							if (CollectionUtils.isNotEmpty(sendMsgResultList)) {
								int saveMsgOperationResult = workOrderRepairDao.saveMsgOperation(sendMsgResultList);
							}
						}
					} else {
						//只有服务站报的单子，可发送消息通知
						Integer orderSource = (Integer) workOrderMap.get("OrderSource");
						if (orderSource == 1 || orderSource == 3) {
							map.put("roleNames", "'站长','服务商信息员'");
							map.put("roleNo", "'R0041','R0069'");
							List<Map<String, Object>> sendList = new ArrayList<Map<String, Object>>();
							sendList = workOrderRepairDao.getSendList(map,Arrays.asList("R0041","R0069"));
							if (null != sendList && sendList.size() > 0) {
								//准备发送信息
								Map<String, Object> otherMap = new HashMap<String, Object>();
								String smsgbody = "您有工单取消，工单号 " + oldOrderNo + "，";
								if(OrderChannel == 1){
									smsgbody = smsgbody + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
								}
								smsgbody = smsgbody + "请查看!";
								String stransmsg = "您有工单取消，工单号 " + oldOrderNo + "，";
								if(OrderChannel == 1){
									stransmsg = stransmsg + "属于\"" + sellType + "\"" + (StringUtils.isNotBlank(serviceSubtype) ? "-" + serviceSubtype : "") + "，";
								}
								stransmsg = stransmsg + "请查看!";
								otherMap.put("msgBody", smsgbody);
								otherMap.put("msgTransMsg", stransmsg);
								otherMap.put("msgTitle", "工单取消");
								otherMap.put("function", 9);
								otherMap.put("category", 4);
								otherMap.put("Creator", id);
								otherMap.put("CreateTime", realCurrentTime);
								// 开始发送消息(返回结果集为发送结果，要存入数据库，作为记录)
								List<Map<String, Object>> sendMsgResultList = asyncTask.sendMsg(workOrderMap,
										sendList, 1, 1, otherMap);
								// 将信息发送结果记录到数据库
								if (CollectionUtils.isNotEmpty(sendMsgResultList)) {
									int saveMsgOperationResult = workOrderRepairDao.saveMsgOperation(sendMsgResultList);
								}
							}
						}
					}
					try {
						obj.put("status", 0);
						obj.put("msg", "");
						obj.put("data", "");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					ParameterTool.writeResponse(response, obj.toString());
					// 插入消息提醒记录表
					// int insertNotifyRecord1 =
					// serviceManagerAffirmDao.insertNotifyRecord1(map);
					// int insertNotifyRecord2 =
					// serviceManagerAffirmDao.insertNotifyRecord2(map);
					// System.out.println(insertNotifyRecord1+"---"+insertNotifyRecord2);
				}else {
					obj.put("status", SMSEnum.type21.getIndex());
					obj.put("msg", SMSEnum.type21.getName());
					obj.put("data", "");
					// 主动回滚事务
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
					//返回客户
					ParameterTool.writeResponse(response, obj.toString());
					return null;
				}
			}

		} catch (Exception ex) {
			// TODO: handle exception
			log.error(ex.getMessage(), ex);
			ParameterTool.writeErrorResponse(response);
			// 主动回滚事务
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
		}
		return null;
	}

	public Map<String, Object> OrderStatusToCrmMap(Map<String, Object> orgOrderMap, Map<String, Object> map,int serviceChannel) {
		Map<String, Object> tbMap = new HashMap<String, Object>();
		if (serviceChannel == 3){
			tbMap.put("orderNo", orgOrderMap.get("newOrderNo"));
			if (!"".equals(MapUtils.getString(orgOrderMap, "OrderNoCrm", ""))) {
				tbMap.put("CRMNo", orgOrderMap.get("OrderNoCrm"));
			}

			tbMap.put("newOrderStatus", 36);

			tbMap.put("oldOrderNo", map.get("oldOrderNo"));
			tbMap.put("billStatus", 3);
			tbMap.put("refuseType", map.get("RefuseType"));// 2 用户不需要维修
			tbMap.put("refuseReason", map.get("RefuseContent"));
			tbMap.put("actionTime", LocalTimeUtil.getRealCurrentTime());
			tbMap.put("directorName", map.get("contact"));
			tbMap.put("directorPhone", map.get("phone"));
			tbMap.put("stationNo", map.get("BusinessNo"));
		}else
		{
			tbMap.put("orderNo", orgOrderMap.get("OrderNo"));
			if (!"".equals(MapUtils.getString(orgOrderMap, "OrderNoCrm", ""))) {
				tbMap.put("CRMNo", orgOrderMap.get("OrderNoCrm"));
			}
			tbMap.put("oldOrderNo", "");
			tbMap.put("billStatus", 3);
			tbMap.put("refuseType", map.get("RefuseType"));// 2 用户不需要维修
			tbMap.put("refuseReason", map.get("RefuseContent"));
			tbMap.put("actionTime", LocalTimeUtil.getRealCurrentTime());
			tbMap.put("directorName", map.get("contact"));
			tbMap.put("directorPhone", map.get("phone"));
			tbMap.put("stationNo", "");
		}

		return tbMap;
	}
	public Map<String, Object> OrderStatusToCrmMapByServiceManager(Map<String, Object> orderMap,Map<String, Object> map) {
		Map<String, Object> tbMap = new HashMap<String, Object>();
		tbMap.put("orderNo", orderMap.get("OrderNo"));
		tbMap.put("CRMNo", orderMap.get("OrderNoCrm"));
		tbMap.put("billStatus", 3);
		tbMap.put("refuseType", map.get("RefuseType"));// 2 用户不需要维修
		tbMap.put("refuseReason", map.get("RefuseContent"));
		tbMap.put("actionTime", LocalTimeUtil.getRealCurrentTime());
		tbMap.put("directorName", map.get("contact"));
		tbMap.put("directorPhone", map.get("phone"));
		tbMap.put("stationNo", map.get("BusinessNo"));

		return tbMap;
	}


	/**
	 *
	 * @param map
	 * @param workOrderMap
	 * @return
	 */
	public Map<String, Object> CRM_WorkOrder_Convert(Map<String, Object> workOrderMap, Map<String, Object> map, Integer orderStatus) {
		Map<String, Object> newMap = new HashMap<String, Object>();
		if (workOrderMap.containsKey("OrderNo")) {
			newMap.put("OrderNo", workOrderMap.get("newOrderNo"));
		}
		if (workOrderMap.containsKey("OrderNoCrm")) {
			newMap.put("OrderNoCrm", workOrderMap.get("OrderNoCrm"));
		}
		if (workOrderMap.containsKey("OrderChannel")) {
			newMap.put("OrderChannel", workOrderMap.get("OrderChannel"));
		}
		if (workOrderMap.containsKey("OrderSource")) {
			newMap.put("OrderSource", workOrderMap.get("OrderSource"));
		}
		if (workOrderMap.containsKey("ESN")) {
			newMap.put("ESN", workOrderMap.get("ESN"));
		}
		if (workOrderMap.containsKey("VIN")) {
			newMap.put("VIN", workOrderMap.get("VIN"));
		}
		if (workOrderMap.containsKey("EngineType")) {
			newMap.put("EngineType", workOrderMap.get("EngineType"));
		}
		if (workOrderMap.containsKey("SMN")) {
			newMap.put("SMN", workOrderMap.get("SMN"));
		}
		if (workOrderMap.containsKey("OEMID")) {
			newMap.put("OEMID", workOrderMap.get("OEMID"));
		}
		if (workOrderMap.containsKey("OEMName")) {
			newMap.put("OEMName", workOrderMap.get("OEMName"));
		}
		if (workOrderMap.containsKey("CustomerId")) {
			newMap.put("CustomerId", workOrderMap.get("CustomerId"));
		}
		if (workOrderMap.containsKey("CustomerName")) {
			newMap.put("CustomerName", workOrderMap.get("CustomerName"));
		}
		if (workOrderMap.containsKey("CustomerPhone")) {
			newMap.put("CustomerPhone", workOrderMap.get("CustomerPhone"));
		}
		if (workOrderMap.containsKey("LocLon")) {
			newMap.put("LocLon", workOrderMap.get("LocLon"));
		}
		if (workOrderMap.containsKey("LocLat")) {
			newMap.put("LocLat", workOrderMap.get("LocLat"));
		}
		if (workOrderMap.containsKey("Location")) {
			newMap.put("Location", workOrderMap.get("Location"));
		}
		if (workOrderMap.containsKey("AuditLevel")) {
			newMap.put("AuditLevel", workOrderMap.get("AuditLevel"));
		}
		if (workOrderMap.containsKey("CurrentLevel")) {
			newMap.put("CurrentLevel", workOrderMap.get("CurrentLevel"));
		}
		if (workOrderMap.containsKey("CustomerComplaint")) {
			newMap.put("CustomerComplaint", workOrderMap.get("CustomerComplaint"));
		}
		if (workOrderMap.containsKey("ServiceStationId")) {
			newMap.put("ServiceStationId", map.get("ServiceStationId"));
		}
		if (workOrderMap.containsKey("ServiceCarId")) {
			newMap.put("ServiceCarId", "");
		}
		if (workOrderMap.containsKey("ServiceCarNo")) {
			newMap.put("ServiceCarNo", "");
		}
		if (workOrderMap.containsKey("IsOutside")) {
			newMap.put("IsOutside", workOrderMap.get("IsOutside"));
		}

		if (workOrderMap.containsKey("GuessDistance")) {
			newMap.put("GuessDistance",  MapUtils.getFloatValue(map,"distance",0));  //map.get("distance")
		}
		if (workOrderMap.containsKey("PrincipalId")) {
			newMap.put("PrincipalId", map.get("updator"));
		}

		if (workOrderMap.containsKey("OrderStatus")) {
			newMap.put("OrderStatus", orderStatus);
		}

		if (workOrderMap.containsKey("RelOrderId")) {
			newMap.put("RelOrderId", null);
		}
		if (workOrderMap.containsKey("RelOrderIdOld")) {
			newMap.put("RelOrderIdOld", map.get("oldOrderId"));
		}

		if (workOrderMap.containsKey("TransferTime")) {
			newMap.put("TransferTime", map.get("updateTime"));
		}
		if (workOrderMap.containsKey("TransferReason")) {
			newMap.put("TransferReason", map.get("RefuseContent"));
		}
		if (workOrderMap.containsKey("Creator")) {
			newMap.put("Creator", map.get("updator"));
		}

		if (workOrderMap.containsKey("CreateTime")) {
			newMap.put("CreateTime", workOrderMap.get("CreateTime"));
		}

		if (workOrderMap.containsKey("EngineMsgId")) {
			newMap.put("EngineMsgId", workOrderMap.get("EngineMsgId"));
		}
		if (workOrderMap.containsKey("OrderType")) {
			newMap.put("OrderType", workOrderMap.get("OrderType"));
		}
		if (workOrderMap.containsKey("WorkHours")) {
			newMap.put("WorkHours", workOrderMap.get("WorkHours"));
		}
		if (workOrderMap.containsKey("WorkMileages")) {
			newMap.put("WorkMileages", workOrderMap.get("WorkMileages"));
		}

		//NatureClaim, EmergencyMode
		if (workOrderMap.containsKey("NatureClaim")) {
			newMap.put("NatureClaim", workOrderMap.get("NatureClaim"));
		}
		if (workOrderMap.containsKey("EmergencyMode")) {
			newMap.put("EmergencyMode", workOrderMap.get("EmergencyMode"));
		}

		/**
		 * 2023/1/13 新增 变速箱号、保修性质、故障发生时间
		 */
		if (workOrderMap.containsKey("AmtNo")) {
			newMap.put("AmtNo", workOrderMap.get("AmtNo"));
		}
		if (workOrderMap.containsKey("WarrantyNature")) {
			newMap.put("WarrantyNature", workOrderMap.get("WarrantyNature"));
		}
		if (workOrderMap.containsKey("FaultHappenTime")) {
			newMap.put("FaultHappenTime", workOrderMap.get("FaultHappenTime"));
		}

		return newMap;
	}

	/**
	 * 将工单信息同步至CRM(由于CRM接口与APP接口的字段名称不一致，所以要进行相关字段的转换)
	 *
	 * @param map
	 *            工单来源（0：客户，1：服务站）
	 * @return
	 */
	public Map<String, Object> APP2CRM_WorkOrder_Convert(Map<String, Object> map) {
		Map<String, Object> newMap = new HashMap<String, Object>();
		// if(map.containsKey("OrderNo")) {
		newMap.put("orderNo", map.get("newOrderNo"));
		// }
		// if(map.containsKey("ESN")) {
		newMap.put("ESN", map.get("ESN"));
		// }
		// if(map.containsKey("VIN")) {
		newMap.put("equipmentNo", map.get("VIN"));
		// }
		// if(map.containsKey("CustomerName")) {
		newMap.put("customerName", map.get("CustomerName"));
		// }
		// if(map.containsKey("CustomerPhone")) {
		newMap.put("customerPhone", map.get("CustomerPhone"));
		// }
		// if(map.containsKey("Location")) {
		newMap.put("faultLocation", map.get("Location"));
		// }
		// if(map.containsKey("LocLat")) {
		newMap.put("faultLat", map.get("LocLat"));
		// }
		// if(map.containsKey("LocLon")) {
		newMap.put("faultLon", map.get("LocLon"));
		// }
		if (map.containsKey("ServiceCarNo")) {
			newMap.put("serviceCar", map.get("ServiceCarNo"));
		}
		// if(map.containsKey("IsOutside")) {
		newMap.put("needGoOut", map.get("IsOutside"));
		// }
		// if(map.containsKey("CustomerComplaint")) {
		newMap.put("faultDesc", map.get("CustomerComplaint"));
		// }
		if (map.containsKey("StationNo")) {
			// 根据页面传给我的服务站ID查询服务站编号
			// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			newMap.put("stationNo", map.get("StationNo"));
		}
		if (map.containsKey("StationName")) {
			// 根据页面传给我的服务站ID查询服务站编号
			// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			newMap.put("stationName", map.get("StationName"));
		}
		if (map.containsKey("OrderChannel")) {
			newMap.put("serviceChannel", map.get("OrderChannel"));
		}
		// 服务站还是用户报修
		// if(map.containsKey("OrderSource")) {
		newMap.put("orderSource", map.get("OrderSource"));
		// }
		// if(map.containsKey("ProcessorName")) {
		newMap.put("creatPerson", map.get("ProcessorName"));
		// }
		// if(map.containsKey("CreateTime")) {
		newMap.put("creatTime", map.get("CreateTime"));
		// }
		if (map.containsKey("WorkHours")) {
			// 根据页面传给我的服务站ID查询服务站编号
			// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			newMap.put("workHours", map.get("WorkHours"));
		}
		if (map.containsKey("WorkMileages")) {
			// 根据页面传给我的服务站ID查询服务站编号
			// ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
			newMap.put("workMileages", map.get("WorkMileages"));
		}
		return newMap;
	}

	public Map<String, Object> XCECNewOrderStatusToCrmMap(Map<String, Object> orgOrderMap, Map<String, Object> map) {
		Map<String, Object> tbMap = new HashMap<String, Object>();
		tbMap.put("orderNo", orgOrderMap.get("newOrderNo"));
		if (!"".equals(MapUtils.getString(orgOrderMap, "OrderNoCrm", ""))) {
			tbMap.put("CRMNo", orgOrderMap.get("OrderNoCrm"));
		}
		tbMap.put("oldOrderNo", map.get("oldOrderNo"));
		tbMap.put("billStatus", 4);// 待服务商接单
		tbMap.put("refuseType", "");// 2 用户不需要维修
		tbMap.put("refuseReason", "");
		tbMap.put("actionTime", LocalTimeUtil.getRealCurrentTime());
		tbMap.put("directorName", map.get("contact"));
		tbMap.put("directorPhone", map.get("phone"));
		tbMap.put("stationNo", map.get("BusinessNo"));
		tbMap.put("stationName",MapUtils.getString(map,"StationName",""));

		tbMap.put("phoneIMEI",MapUtils.getString(map,"IMEI",""));
		tbMap.put("positionLat",MapUtils.getFloatValue(map,"PositionLat",0));
		tbMap.put("positionLon",MapUtils.getFloatValue(map,"PositionLon",0));
		tbMap.put("location",MapUtils.getString(map,"Location",""));
		return tbMap;
	}
}
